package com.jie.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jie.dto.CommentDTO;
import com.jie.entity.Article;
import com.jie.entity.Comment;
import com.jie.enums.CommentTargetEnum;
import com.jie.enums.FileType;
import com.jie.mapper.ArticleMapper;
import com.jie.mapper.CommentMapper;
import com.jie.service.ICommentService;
import com.jie.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 论坛评论表 服务实现类
 * </p>
 *
 * @author jie
 * @since 2024-05-29
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Comment checkCommentById(Integer commentId) {
        return commentMapper.selectById(commentId);
    }

    @Override
    public Boolean deleteCommentById(Integer commentId) {
        return commentMapper.deleteById(commentId) > 0;
    }

    @Override
    public Boolean addComment(CommentDTO commentDto) {
        //0.从前端获取的属性有：评论内容，评论用户名，评论目标类型，评论目标id(parent_id)
        //1.判断评论对象是文章还是评论
        String targetType = commentDto.getTargetType();
        Integer userId = UserUtils.getLoginUser().getId();

        //2. comment_uid评论用户使用threadLocal存储的用户id，
        // likeCount设置为0，is_check设置为0，commented_count设置为0;
        Comment comment = Comment.builder()
                .commentContent(commentDto.getCommentContent())
                .targetType(commentDto.getTargetType())
                .targetUid(commentDto.getTargetUid())
                .parentId(commentDto.getParentId())
                .likeCount(0)
                .commentedCount(0)
                .isCheck(0)
                .commentUid(userId)
                .build();
        if(commentDto.getTargetType().equals(CommentTargetEnum.ARTICLE.getValue())){
            //插入对应的文章评论区数据库，即对文章评论数+1
            //判断是否目标对象是否为空
//            if(Objects.isNull(comment.getParentId())){

//            }
            articleMapper.addCommentCount(comment.getParentId(),1);
        }
        else if(commentDto.getTargetType().equals(CommentTargetEnum.COMMENT.getValue())){
            //插入对应的评论的评论区数据库，即对评论评论数+1
            commentMapper.addCommentCount(comment.getParentId(),1);
        }
        //3.更新文章的评论数量
        //builder封装插入
        return commentMapper.insert(comment)>0;
    }

    @Override
    public List<CommentDTO> getCommentList() {
        return commentMapper.selectList();
    }

    //将点赞数字人，评论，帖子全都放在likeController模块
}
